package org.joy.generator;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.swing.JOptionPane;

import org.joy.config.Configuration;
import org.joy.config.TypeMapping;
import org.joy.config.model.DatabaseElement;
import org.joy.config.model.TemplateElement;
import org.joy.db.Database;
import org.joy.db.DatabaseFactory;
import org.joy.db.model.Table;
import org.joy.generator.engine.TemplateEngine;
import org.joy.util.ClassloaderUtility;
import org.joy.util.StringUtil;

public class Main {

	public static void main(String[] args) {

		String classPath = ClassloaderUtility.getClassPath();
		classPath = classPath + "etc\\";
		System.out.println(classPath);
		Configuration configuration = new Configuration(classPath);
		try {
			configuration.loadConfiguration();
		} catch (Exception e) {
			e.printStackTrace();
		}
		TypeMapping typeMapping = new TypeMapping(classPath);
		try {
			typeMapping.loadMapping();
		} catch (Exception e) {
			e.printStackTrace();
		}
		List<DatabaseElement> dataBases = configuration.getDatabases();
		for (DatabaseElement oneDataBase : dataBases) {
			try {
				processOneDatabase(oneDataBase, configuration.getTemplates(), String typeMapping);
			} catch (ClassNotFoundException e) {
				e.printStackTrace();
			} catch (InstantiationException e) {
				e.printStackTrace();
			} catch (IllegalAccessException e) {
				e.printStackTrace();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}

	public static void processOneDatabase(DatabaseElement oneDataBase, List<TemplateElement> templates, TypeMapping typeMapping) throws ClassNotFoundException, InstantiationException, IllegalAccessException, SQLException {
		
		List<String> tableNames = new ArrayList<String>();
		
		String schemaPattern = oneDataBase.getSchema();
		Connection connection = oneDataBase.connect();
		ResultSet rs = connection.getMetaData().getTables(null, schemaPattern, "%", null);
		while (rs.next()) {
			String tableSchema = rs.getString(2);
			String tableName = rs.getString(3);
			if (StringUtil.isNotEmpty(tableSchema)) {
				tableName = tableSchema + "." + tableName;
			}
			tableNames.add(tableName);
		}
		
        Database db = DatabaseFactory.createDatabase(connection, typeMapping);
        for(String tableName : tableNames){
            Table tableModel = db.getTable(null, oneDataBase.getSchema(), tableName);
            processSelectedTemplates(templates, );
        }
		
	}
	

    private static void processSelectedTemplates(Object[] selectedTemplateElements, String targetProject, String basePackage){
        configuration.setTagertProject(targetProject);
        configuration.setBasePackage(basePackage);
        configuration.setModuleName(moduleName);

        tableModel.setTableAlias(tableAlias);

        Map<String, Object> model = new HashMap<String, Object>();
        model.put("tagertProject", configuration.getTagertProject());
        model.put("basePackage", configuration.getBasePackage());
        model.put("moduleName", configuration.getModuleName());
        model.put("table", tableModel);

        for (TemplateElement templateElement : configuration.getTemplates()) {
            templateElement.setSelected(false);
        }


        int count = selectedTemplateElements.length;
        for (int i=0;i<count; i++) {
            try {
                TemplateElement templateElement = (TemplateElement) selectedTemplateElements[i];
                templateElement.setSelected(true);

                TemplateEngine templateEngine = engineBuilder.getTemplateEngine(templateElement.getEngine());
                if(templateEngine==null){
                    JOptionPane.showMessageDialog(this, "没有对应的模板引擎: "+templateElement.getEngine(), "错误", JOptionPane.ERROR_MESSAGE);
                } else {
                    templateEngine.processToFile(model, templateElement);
                }
            } catch (Exception e) {
                LOGGER.info(e.getMessage(), e);
                JOptionPane.showMessageDialog(this, e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
            }
        }
        configuration.save();
        JOptionPane.showMessageDialog(this, "生成完毕.", "提示", JOptionPane.INFORMATION_MESSAGE);
    }

}
